package ua.edu.nuos.jeetraining2012.cms.ui.views;

import com.vaadin.data.validator.AbstractValidator;
import com.vaadin.data.validator.EmailValidator;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.shared.ui.MarginInfo;
import com.vaadin.ui.*;
import com.vaadin.ui.themes.Reindeer;

import java.io.IOException;
import java.util.Properties;

/**
 * @author Victor N. Ganichev victor.ganichev@gmail.com
 * @version 1.0 Date: 10.11.13 Time: 21:35
 * @since 1.0
 */
public class LoginView extends CustomComponent implements View, Button.ClickListener {

    protected Properties properties = new Properties();

    protected String validLogin;

    protected String validPassword;

    public static final String NAME = "login";

    private final TextField user;

    private final PasswordField password;

    private final Button loginButton;

    public LoginView() {
        setSizeFull();

// Create the user input field
        user = new TextField("User:");
        user.setWidth("300px");
        user.setRequired(true);
        user.setInputPrompt("Your username (eg. joe@email.com)");
        user.addValidator(new EmailValidator("Username must be an email address"));
        user.setInvalidAllowed(false);

// Create the password input field
        password = new PasswordField("Password:");
        password.setWidth("300px");
        password.addValidator(new PasswordValidator());
        password.setRequired(true);
        password.setValue("");
        password.setNullRepresentation("");

// Create login button
        loginButton = new Button("Login", this);

// Add both to a panel
        VerticalLayout fields = new VerticalLayout(user, password, loginButton);
        fields.setCaption("Please login to access the application.");
        fields.setSpacing(true);
        fields.setMargin(new MarginInfo(true, true, true, false));
        fields.setSizeUndefined();

// The view root layout
        VerticalLayout viewLayout = new VerticalLayout(fields);
        viewLayout.setSizeFull();
        viewLayout.setComponentAlignment(fields, Alignment.MIDDLE_CENTER);
        viewLayout.setStyleName(Reindeer.LAYOUT_BLUE);
        setCompositionRoot(viewLayout);
    }

    @Override
    public void enter(ViewChangeListener.ViewChangeEvent event) {
        // focus the username field when user arrives to the login view
        user.focus();
    }

    //
// Validator for validating the passwords
//
    private static final class PasswordValidator extends AbstractValidator<String> {

        public PasswordValidator() {
            super("The password provided is not valid");
        }

        @Override
        protected boolean isValidValue(String value) {
            //
            // Password must be at least 8 characters long and contain at least
            // one number
            //
            if (value != null
                    && (value.length() < 8 || !value.matches(".*\\d.*"))) {
                return false;
            }
            return true;
        }

        @Override
        public Class<String> getType() {
            return String.class;
        }

    }

    @Override
    public void buttonClick(Button.ClickEvent event) {
        readCreditFile();
        if (!user.isValid() || !password.isValid()) {
            return;
        }

        String username = user.getValue();
        String password = this.password.getValue();

        boolean isValid = username.equals(this.validLogin) && password.equals(this.validPassword);

        if (isValid) {
            // Store the current user in the service session
            getSession().setAttribute("user", username);

            // Navigate to main view
            getUI().getNavigator().navigateTo("");

        } else {

            // Wrong password clear the password field and refocuses it
            this.password.setValue(null);
            this.password.focus();
        }
    }

    protected void readCreditFile() {
        String validLogin, validPasswd;
        try {
            properties.load(LoginView.class.getClassLoader().getResourceAsStream("admin/admin.properties"));
        } catch (IOException e) {
            validLogin = "odmin";
            validPasswd = "dr0wssap";
        }

        if (properties != null) {
            validLogin = properties.getProperty("login");
            validPasswd = properties.getProperty("password");
        } else {
            validLogin = "odmin";
            validPasswd = "dr0wssap";
        }
        this.validLogin = validLogin;
        this.validPassword = validPasswd;
    }

}
